package ru.gr.alphaversion;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.Toast;

		public class Orders extends Activity implements OnClickListener {

			private static final int DIALOG_PAUSED_ID = 0;
			private static final int DIALOG_GAMEOVER_ID = 1;
			static String[] inames, iname, iprices, iquas, iids, idescs, idesc, iprice, iqua, iid, iidsn, iidn, iinamesn ,inamen;
			public String value = null;
			public int con,tcon,scon;
			public static String id_item, name_item, price_item, desc, qua_item;
			final String LOG_TAG = "myLogs";
			  
			  ExpandableListView elvMain;
			  AdapterHelper ah;
			  SimpleExpandableListAdapter adapter;
			

			@Override
				  /** Called when the activity is first created. */
				  public void onCreate(Bundle savedInstanceState) {
				    super.onCreate(savedInstanceState);
				    setTheme(android.R.style.Theme_Light_NoTitleBar_Fullscreen);
				    setContentView(R.layout.orders);
				    
				    View orcrButton = findViewById(R.id.order_create);
			        orcrButton.setOnClickListener(this);
			        
			        View orrshButton = findViewById(R.id.order_refresh);
			        orrshButton.setOnClickListener(this);
			        Main.checkk = 0;
			        
			
			        showDialog(3);
				    getList();
				  }
			protected void onResume() {
				super.onResume();
				Main.checkk = 0;
			
			}

			public String[] ResizeArrary(String [] arr, Integer c )   {
			    String[] array2 = new String[c];
			    for (int i = 0; i < c; i++) {
			        array2[i] = arr[i];
			    }
			    return array2;    
			}  
			
			public void onClick(View v) {
				switch (v.getId()) {
		    	case R.id.order_create: 
		    		//Toast.makeText(this, "Qqqq", Toast.LENGTH_LONG).show();
		    		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		    		alert.setTitle("Введите название нового заказа");
		    		// Set an EditText view to get user input
		    		final EditText input = new EditText(this);
		    		alert.setView(input);
		    		alert.setPositiveButton("Создать", new DialogInterface.OnClickListener() {
		    			public void onClick(DialogInterface dialog, int whichButton) {
		    				String value = input.getText().toString();
		    				Main m = new Main();
		    				m.addNameList(value);
		    				getList();
		    			}
		    		});
		    		alert.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
		    			public void onClick(DialogInterface dialog, int whichButton) {
		    				// Canceled.
		    			}
		    		});
		    		alert.show();
		    	case R.id.order_refresh:
		    		getList();
				}
			}
			
			
			 @Override
		        protected Dialog onCreateDialog(int id) {
		            LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
		            View layout = inflater.inflate(R.layout.log_dialog, (ViewGroup) findViewById(R.id.layout_root));
		            //final EditText inputt = (EditText) layout.findViewById(R.id.editText1);
		           // text.setText("Hello, layout.layout_root!");
		            AlertDialog.Builder alert = null;
		            alert = new AlertDialog.Builder(this);
		            alert.setView(layout);
		            alert.setTitle("Введите логин и пароль");
		            final EditText inputt = (EditText) layout.findViewById(R.id.editText1);
                    final EditText inputt1 = (EditText) layout.findViewById(R.id.editText2);
		            alert.setCancelable(false);
		            alert.setNegativeButton("Выйти", new DialogInterface.OnClickListener() {

		                public void onClick(DialogInterface dialog, int id) {
		                    dialog.cancel();
		                    finish();
		                }
		            });

		            alert.setPositiveButton("Да", new DialogInterface.OnClickListener() {

		                public void onClick(DialogInterface dialog, int id) {
		                	String value = inputt.getText().toString();
							String value1 = inputt1.getText().toString();
							Main.MId = "106";
						//	Main.MId = login(value,value1);
		                   // finish();
		                }
		            });
		            Dialog dialog = null;
		            dialog = new Dialog(this);
		            switch (id) {
		                case DIALOG_PAUSED_ID:
		                    dialog.setTitle("DIALOG_PAUSED_ID");
		                    dialog.setContentView(R.layout.log_dialog);
		                    final EditText inputtt = (EditText) layout.findViewById(R.id.editText1);
		                    final EditText inputtt1 = (EditText) layout.findViewById(R.id.editText2);
		                //    textd.setText("Hello, layout.custom_dialog!");
		                    return dialog;
		                case DIALOG_GAMEOVER_ID:
		                    dialog.setTitle("DIALOG_GAMEOVER_ID");
		                    return dialog;
		                default:
		                    return alert.create();
		            }
		        }
			
			
			public String login(String value, String value1) {
				
				  GetJSON json = new GetJSON();
				    try {
							String gg = json.postData("",value, "QLogin", value1, this);
							JSONObject jsonObject = new JSONObject(gg);
							
							if(gg!="") {
							if((jsonObject.getString("error").equals("2"))||(jsonObject.getString("error").equals("1"))) {
								Builder alert = new AlertDialog.Builder(this);
					            alert.setTitle("Ошибка авторизации");
					            alert.setMessage("Неверный логин или пароль");
					            alert.setPositiveButton("Повтор", new DialogInterface.OnClickListener() {
					            	public void onClick(DialogInterface dialog, int which) {
					            		showDialog(3);
					            	}
					            });
					            /*alert.setNegativeButton("Выход", new OnClickListener() {
					                public void onClick(DialogInterface dialog, int arg1) {
					                    dialog.dismiss();
					                    onBackPressed();
					                }

									public void onClick(View v) {
										// TODO Auto-generated method stub
										
									}
					            });*/
					            alert.create().show();
							}
								else {
								
											String MId = jsonObject.getString("id");
											Toast.makeText(this, MId, Toast.LENGTH_LONG).show();
											return MId;
							//abs = false;
							//Main.id_l.setText(Main.list_id);
							//id_l = (TextView)findViewById(R.id.e_id);
					        //id_l.setText(Main.list_id);
						
						
								}
							}
						else {
							finish();
							//Toast.makeText(this, "Нет соединения с сервером", Toast.LENGTH_LONG).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						Builder alert = new AlertDialog.Builder(this);
			            alert.setTitle("Ошибка авторизации");
			            alert.setMessage("Неверный логин или пароль");
			            alert.setPositiveButton("Повтор", new DialogInterface.OnClickListener() {
			            	public void onClick(DialogInterface dialog, int which) {
			            		showDialog(3);
			            	}
			            });
			            /*alert.setNegativeButton("Выход", new OnClickListener() {
			                public void onClick(DialogInterface dialog, int arg1) {
			                    dialog.dismiss();
			                    onBackPressed();
			                }

							public void onClick(View v) {
								// TODO Auto-generated method stub
								
							}
			            });*/
			            alert.create().show();
					}
					return Main.MId;
				   
			}
			
			
			
			
			public void getList() {
				String [] inames = new String[500];
			    final String [] iids = new String[500];
			    String [] inamesn = new String[500];
			    final String [] iidsn = new String[500];
			    GetJSON json = new GetJSON();
				try {
					String gg = json.postData( "", "", "QGetLists", "", this);
					JSONObject jsonObject = new JSONObject(gg);
					if(gg!="") {
						if(jsonObject.getString("error").equals("1")) {
							Toast.makeText(this, R.string.no_name, Toast.LENGTH_LONG).show();
							Orders.this.finish();
						} else {
							
							JSONArray jsonObject_1 = jsonObject.getJSONArray("lists");
				
							scon = jsonObject_1.length();
							tcon = 0;
							int j = 0;
														//
							for (int i = 0; i<(jsonObject_1.length()); i++) {
								
								desc = jsonObject_1.getJSONObject(i).getString("CNAME");
								if (jsonObject_1.getJSONObject(i).getString("STATE").equals("2"))
									desc = jsonObject_1.getJSONObject(i).getString("CNAME")+"  - Отправлен";
								id_item = jsonObject_1.getJSONObject(i).getString("ID");
							if ((jsonObject_1.getJSONObject(i).getString("START").equals("1"))&&!(jsonObject_1.getJSONObject(i).getString("STATE").equals("2")))
							{
								 iidsn[j] =  id_item;
								 inamesn[j] =  id_item+"    "+desc;
								 j++;
								 tcon++;
							}
							else {
							iids[i-tcon] = id_item;
							inames[i-tcon] = id_item+"    "+desc;}
							
					
							
															
						}
							con = scon-tcon;
						}
					} else {
						
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String [] iid = new String[con];
				String [] iname = new String[con];
				if (tcon==0)
				{
				String [] iidn = new String[tcon+1];
				String [] inamen = new String[tcon+1];
				Orders.iidn = ResizeArrary(iidsn,tcon+1);
				Orders.inamen = ResizeArrary(inamesn,tcon+1);
				} else 
				{
					String [] iidn = new String[tcon];
					String [] inamen = new String[tcon];
					Orders.iidn = ResizeArrary(iidsn,tcon);
					Orders.inamen = ResizeArrary(inamesn,tcon);
				}
				
				Orders.iid = ResizeArrary(iids,con);
				Orders.iname = ResizeArrary(inames,con);
				
				if (tcon==0)
				{
				Orders.inamen[0]="Нет заказов";	
				}
	

			    
			    
			    
			    // создаем адаптер
		        ah = new AdapterHelper(this,Orders.inamen,Orders.iname);
		        adapter = ah.getAdapter();		        
		        elvMain = (ExpandableListView) findViewById(R.id.elvMain);
		        elvMain.setAdapter(adapter);
		        
		        // нажатие на элемент
		        elvMain.setOnChildClickListener(new OnChildClickListener() {
		      public boolean onChildClick(ExpandableListView parent, View v,
		          int groupPosition,   int childPosition, long id) {
		        Log.d(LOG_TAG, "onChildClick groupPosition = " + groupPosition + 
		                " childPosition = " + childPosition + 
		                " id = " + id);
		        if (groupPosition==1){
		        		        
		        Main.list_id = iids[childPosition];
		        Main mn = new Main();
			       
	        	mn.orderItemList();
		        }
		        else
		        	if (tcon>0){
		        	Main.list_id = iidsn[childPosition];
		        	Main mn = new Main();
		 	       
		        	mn.orderItemList();
		        	}
	        	
		        return false;
		      }
		    });
		        
		        // нажатие на группу
		        elvMain.setOnGroupClickListener(new OnGroupClickListener() {
		      public boolean onGroupClick(ExpandableListView parent, View v,
		          int groupPosition, long id) {
		        Log.d(LOG_TAG, "onGroupClick groupPosition = " + groupPosition + 
		                " id = " + id);
		      
		      //  if ((groupPosition == 0)&&(tcon==0)) return true;
		        
		        return false;
		      }
		    });
		        
		        // сворачивание группы        
		        elvMain.setOnGroupCollapseListener(new OnGroupCollapseListener() {
		      public void onGroupCollapse(int groupPosition) {
		        Log.d(LOG_TAG, "onGroupCollapse groupPosition = " + groupPosition);
		      
		      }
		    });
		        
		        // разворачивание группы
		        elvMain.setOnGroupExpandListener(new OnGroupExpandListener() {
		      public void onGroupExpand(int groupPosition) {
		        Log.d(LOG_TAG, "onGroupExpand groupPosition = " + groupPosition);
		      
		      }
		    });
		        
		        // разворачиваем группу с позицией 0
		        elvMain.expandGroup(0);
			    
			    
			    
			    
			    
			    
			    
			    
			    
			    
			    
			    
			    
			    
			    
			    
			    
			    
			    
			    
			    
			   
			  
			}
	}



